package org.qpcr.community.project.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hswebframework.ezorm.rdb.mapping.defaults.SaveResult;
import org.hswebframework.web.api.crud.entity.PagerResult;
import org.hswebframework.web.api.crud.entity.QueryParamEntity;
import org.hswebframework.web.crud.service.GenericReactiveCrudService;
// import org.hswebframework.web.exception.BusinessException;
import org.qpcr.community.project.model.entity.DataGroupEntity;
import org.qpcr.community.project.response.DataGroupDetail;
import org.reactivestreams.Publisher;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class DataGroupService extends GenericReactiveCrudService<DataGroupEntity, String> {
    @Resource
    private DataAnalysisExperimentalRecordsService dataAnalysisExperimentalRecordsService;

    /**
     * 根据ID修改分组名称
     */
    public Mono<Integer> updateNameById(String id, String name) {
        // 先校验名称是否已存在（排除当前记录）
        return existsByNameExcludeId(name, id)
                .flatMap(exists -> {
                    if (exists) {
                        return Mono.error(new IllegalArgumentException("分组名称 `" + name + "` 已存在"));
                    }
                    // 名称不存在，执行更新
                    return super.createUpdate()
                            .set(DataGroupEntity::getName, name)
                            .where(DataGroupEntity::getId, id)
                            .execute();
                });
    }

    public Mono<DataGroupDetail> getDetailById(String id) {
        return super.createQuery()
                    .where(DataGroupEntity::getId, id)
                    .fetchOne()
                    .flatMap(entity -> {
                        DataGroupDetail detail = new DataGroupDetail();
                        BeanUtils.copyProperties(entity, detail);

                        // 获取数据数量统计
                        return dataAnalysisExperimentalRecordsService.countByGroupId(id)
                                                                     .map(dataCount -> {
                                                                         detail.setDataCount(dataCount);
                                                                         return detail;
                                                                     });
                    });
    }

    public Mono<PagerResult<DataGroupDetail>> queryPagerWithDataCount(QueryParamEntity query){
        return this.queryPager(query)
                .flatMap(pagerResult -> {
                    List<DataGroupEntity> groupList = pagerResult.getData();
                    if (groupList == null || groupList.isEmpty()) {
                        return Mono.just(PagerResult.of(0, Collections.emptyList(), query));
                    }
                    List<String> groupIds = groupList.stream().map(DataGroupEntity::getId).collect(Collectors.toList());
                    return dataAnalysisExperimentalRecordsService.countByGroupIds(groupIds)
                            .map(countMap -> {
                                List<DataGroupDetail> detailList = new ArrayList<>();
                                for (DataGroupEntity entity : groupList) {
                                    DataGroupDetail detail = new DataGroupDetail();
                                    BeanUtils.copyProperties(entity, detail);
                                    Long count = countMap.getOrDefault(entity.getId(), 0L);
                                    detail.setDataCount(count.intValue());
                                    detailList.add(detail);
                                }
                                return PagerResult.of(pagerResult.getTotal(), detailList, query);
                            });
                });
    }

    @Override
    public Mono<Integer> insert(Publisher<DataGroupEntity> entityPublisher) {
        return Flux.from(entityPublisher)
                .flatMap(entity -> {
                    // 校验name是否已存在
                    return existsByName(entity.getName(),entity.getCreatorId())
                            .flatMap(exists -> {
                                if (exists) {
                                    return Mono.error(new IllegalArgumentException("分组名称 `"+ entity.getName() +"` 已存在"));
                                }
                                return Mono.just(entity);
                            });
                })
                .collectList()
                .flatMap(entities -> super.insert(Flux.fromIterable(entities)));
    }

    public Mono<Boolean> existsByName(String name,String creatorId) {
        return createQuery()
                .is(DataGroupEntity::getName, name)
                .and()
                .is(DataGroupEntity::getCreatorId, creatorId)
                .count()
                .map(count -> count > 0);
    }

    /**
     * 检查指定名称是否存在（排除指定ID的记录）
     */
    public Mono<Boolean> existsByNameExcludeId(String name, String excludeId) {
        return createQuery()
                .where(DataGroupEntity::getName, name)
                .and(DataGroupEntity::getId, excludeId, "!=")
                .count()
                .map(count -> count > 0);
    }
}
